package com.sky.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional //保证数据一致性，要么全成功要么全失败
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //属性拷贝    前提：属性名是完全一样的
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.insert(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //把获取到的dishId插入到dishFlavor
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize()); //开始分页
        Page<DishVO> page =dishMapper.pageQuery(dishPageQueryDTO);

        Long total = page.getTotal();
        List<DishVO> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional //保证数据一致性，要么全成功要么全失败
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除(是否存在启售)
        for (Long id : ids) {
            Dish dish=dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品处于启售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE); //不允许删除异常，需要传一个提示信息最终给前端
            }
        }
        //判断当前菜品是否能狗删除(被套餐管理)
        List<Long> setmealids = setmealDishMapper.getSetmealDishIdsBySetmealId(ids); //setmealids存放的是每个菜对应的套餐id，如果没有则是null
        if (setmealids != null && setmealids.size() > 0) {
            //当菜品被套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }
        //删除菜品
/*        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除关联的口味
            dishFlavorMapper.deleteByDishId(id);
        }*/
        //优化方案:删除菜品id集合，无需遍历
        //根据菜品id集合批量删除菜品 SQL:delete from dish where id in(?,?,?...)
        dishMapper.deleteByIds(ids);
        //根据菜品id集合批量删除关联的口味数据 SQL:delete from dish_flavor where dish_id in(?,?,?...)
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品和口味
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品
        Dish dish=dishMapper.getById(id);
        //根据菜品id查询关联口味
        List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装到VO
        DishVO dishVo=new DishVO();
        BeanUtils.copyProperties(dish,dishVo); //分类名称:private String categoryName;这个无法拷贝是因为Dish没有，而且查询DishVO也不需要
        dishVo.setFlavors(dishFlavors); //赋值一下查询的口味表
        return dishVo;
    }

    /**
     * 修改菜品步骤2
     * 修改菜品和口味
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFalvor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品
        dishMapper.update(dish);
        //删除原有口味，再重新插入
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors=dishDTO.getFlavors(); //得到口味数据
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }


}